import { Router } from 'express';
import { body } from 'express-validator';
import validateFormData from '../helpers/validate_form.js';
import DB from '../models/db.js';

const router = Router();

/**
 * Route to submit employer application (public, no auth required)
 * @POST /employer/submit
 */
router.post('/submit', 
    [
        body('company_name').not().isEmpty().withMessage('公司名称不能为空'),
        body('business_license').not().isEmpty().withMessage('营业执照号不能为空'),
        body('contact_person').not().isEmpty().withMessage('联系人不能为空'),
        body('contact_phone').not().isEmpty().withMessage('联系电话不能为空'),
        body('contact_email').not().isEmpty().isEmail().withMessage('请输入有效的邮箱地址'),
        body('company_address').not().isEmpty().withMessage('公司地址不能为空'),
        body('company_website').optional().isURL().withMessage('请输入有效的网址'),
    ], validateFormData
, async function (req, res) {
    try {
        let modeldata = req.getValidFormData();
        
        // 检查营业执照号是否已存在
        const existingApplication = await DB.EmployerApplications.findOne({
            where: { business_license: modeldata.business_license }
        });

        if (existingApplication) {
            return res.badRequest('该营业执照号已被使用');
        }

        // 设置初始状态为待审核
        modeldata.application_status = 'pending';
        
        // 保存申请记录
        let record = await DB.EmployerApplications.create(modeldata);
        
        // 返回成功信息，但不返回敏感数据
        return res.ok({
            success: true,
            message: '申请提交成功，请等待审核',
            application_id: record.application_id,
            company_name: record.company_name,
            application_status: record.application_status,
            created_at: record.created_at
        });
    } catch(err) {
        console.error('提交申请时出错:', err);
        return res.serverError('提交申请失败，请稍后重试');
    }
});

/**
 * Route to check application status (public, no auth required)
 * @GET /employer/check-status
 */
router.get('/check-status/:business_license',  async function (req, res) {
    try {
        const { business_license } = req.params;
        
        // 查询申请记录
        const application = await DB.EmployerApplications.findOne({
            where: { business_license },
            attributes: ['application_id', 'company_name', 'application_status', 'created_at', 'updated_at', 'review_notes']
        });

        if (!application) {
            return res.notFound('未找到相关申请记录');
        }

        // 返回申请状态信息
        return res.ok({
            success: true,
            application_id: application.application_id,
            company_name: application.company_name,
            application_status: application.application_status,
            created_at: application.created_at,
            updated_at: application.updated_at,
            reviewer_notes: application.reviewer_notes
        });
    } catch(err) {
        console.error('查询申请状态时出错:', err);
        return res.serverError('查询申请状态失败，请稍后重试');
    }
});

export default router; 